#pragma once

#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace LogMoudle;

const std::string default_path = "./dictionary.txt";
const std::string sep = ": ";

class Dict
{
public:
    Dict(const std::string &path = default_path) : _dict_path(path)
    {
    }
    bool LoadDict()
    {
        std::ifstream in(_dict_path); // 打开了一个输入流
        if (!in.is_open())
        {
            LOG(LogLevel::DEBUG) << "打开字典：" << _dict_path << "失败";
            return false;
        }
        // 打开成功了
        std::string line;
        while (std::getline(in, line))
        {                                 // 每次得到一行
            auto pos = line.find(sep);    // 查找分隔符下标
            if (pos == std::string::npos) // 没找到
            {
                LOG(LogLevel::WARNING) << "解析：" << line << "失败";
                continue;
            }
            std::string english = line.substr(0, pos);
            std::string chinese = line.substr(pos + sep.size());
            if (english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARNING) << "没有有效内容：" << line;
                continue;
            }

            _dict.insert(std::make_pair(english, chinese)); // 插入数据对
            LOG(LogLevel::WARNING) << "加载：" << line;
        }

        in.close();
        return true;
    }
    std::string Translate(const std::string &word, InetAddr &client)
    {
        auto iter = _dict.find(word);
        if (iter == _dict.end()) // 没找到
        {
            LOG(LogLevel::DEBUG) << "进入到翻译模块, [" << client.Ip() << "; " << client.Port() << "]#" << word << "->None";
            return "None";
        }
        LOG(LogLevel::DEBUG) << "进入到翻译模块, [" << client.Ip() << "; " << client.Port() << "]#" << word << "->" << iter->second;

        return iter->second;
    }

    ~Dict()
    {
    }

private:
    std::string _dict_path;                             // 路径+文件名
    std::unordered_map<std::string, std::string> _dict; // 字典：哈希映射
};